package current.security.login.action;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import platform.common.action.BaseAction;
import platform.logging.LogContext;

import current.security.init.listener.SessionListener;
import current.security.login.service.UserStateService;
import current.security.user.domain.U_Role;
import current.security.user.domain.User;
import current.security.user.manager.service.UserManagerService;

@Namespace("/login")
@ParentPackage("struts-base")
@Controller("loginAction")
@Scope("prototype")
public class LoginAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	@Resource
	private UserStateService userStateService;
	@Resource
	private UserManagerService userManagerService;
	private Logger loginLog = Logger.getLogger("logininfo");
	private String oldPwd;
	private String newPwd;
	//用户
	private User user;
	//登陆信息
	private String loginMessage;
	
	@Action(value="login",results={@Result(name="success",type="redirect",location="/pages/index.jsp"),@Result(name="failure",location="/main.jsp")})
	public String login() throws Exception {
		String returnStr = "failure";
		String userName = user.getName();
		String password = user.getPassword();
		try {
			//验证登陆名和密码
			user = getState().login(userName,password);
			//验证通过 返回OK
			if (user != null) {
				//查看用户是否在线，在全局范围内查找用户
				SessionListener.isLogined(ServletActionContext.getRequest(),user.getName(),user.getCname());
//				if (SessionListener.isOnline(ServletActionContext.getRequest().getSession(), user.getName())) {
//					System.out.println("..................该用户在线。。");
//				} else {
//					//判断是否已经有此用户登录过，如果有，则将其踢出。前用户失效模式。
//					
//					System.out.println("..................该用户不在线。。");
//				}
				//session中的信息
				Map<String, Object> userMap = new HashMap<String, Object>();
				//角色名
				StringBuffer roleName = new StringBuffer();
				//角色中文名
				StringBuffer roleCname = new StringBuffer();
				//角色ID
				StringBuffer roleId = new StringBuffer();
				StringBuffer roleDFlag = new StringBuffer();
				//用户名
				userMap.put("userName", user.getName());
				//用户中文名
				userMap.put("userCname", user.getCname());
				//用户ID
				userMap.put("userId", user.getId());
				//公司ID
				userMap.put("companyId", user.getCompanyId());
				//部门ID
				userMap.put("departmentId", user.getDepartment().getId());
				
				userMap.put("companyId", user.getDepartment().getCompanyId());
				
				userMap.put("companyName", user.getDepartment().getCompanyName());
				//部门名称
				userMap.put("departmentName", user.getDepartment().getName());
				//角色信息拼串 如  "ROLE_ADMIN,ROLE_USER,ROLE_OTHER,"
				if(user.getRoles() != null){
					for (Iterator<U_Role> iterator = user.getRoles().iterator(); iterator.hasNext();) {
						U_Role roleForm = (U_Role) iterator.next();
						roleName.append(roleForm.getRole().getName());
						roleId.append(roleForm.getRole().getId());
						roleCname.append(roleForm.getRole().getCname());
						roleDFlag.append(roleForm.getRole().getDflag());
						roleCname.append(",");
						roleId.append(",");
						roleName.append(",");
						roleDFlag.append(",");
					}
				}
				userMap.put("roleName", roleName!=null?roleName.toString().replace(",", ""):"");
				userMap.put("roleId", roleId!=null?roleId.toString().replace(",", ""):"");
				userMap.put("roleCname", roleCname!=null?roleCname.toString().replace(",", ""):"");
				userMap.put("roleDFlag", roleDFlag!=null?roleDFlag.toString().replace(",", ""):"");
				ServletActionContext.getRequest().getSession().setAttribute("user", userMap);
				LogContext.info(loginLog,"login",user.getName(),"success");
				returnStr = "success";
			}else{
				LogContext.info(loginLog,"login",userName,"failure");
				setLoginMessage("用户名或者密码错误！请重新输入！");
			}
		} catch (Exception e) {
			log.error("", e);
			LogContext.info(loginLog,"login",userName,"error");
			setLoginMessage("登陆异常！请联系管理员！");
		}
		return returnStr;
	}
	
	@SuppressWarnings("unchecked")
	@Action(value="logout",results={@Result(name="success",type="redirect",location="/main.jsp")})
	public String logout() throws Exception {
		try {
			if(ServletActionContext.getRequest().getSession().getAttribute("user") != null){
				Object userName = ((Map<String,Object>)ServletActionContext.getRequest().getSession().getAttribute("user")).get("userName");
				SessionListener.hUserName.remove(userName);
				SessionListener.hcUserName.remove(userName);		
			}
			ServletActionContext.getRequest().getSession().invalidate();
		} catch (Exception e) {
			log.error("", e);
			throw e;
		}
		return "success";
	}
 
	@Action(value="updatePwd",results={@Result(location="/userManager/pwdUpdate.jsp")})
	public String updatePwd(){
		if(user != null){
			user = (User)userManagerService.getObjectById(User.class, user.getId());
		}
		return SUCCESS;
	}
	
	@Action(value="pwdUpdate")
	public String pwdUpdate(){
		String oldPwdMw = user.getPassword();
		if(user != null){
			user = (User)userManagerService.getObjectById(User.class, user.getId());
		}
		//String spassword = MD5.md5s(oldPwdMw,user.getName());
		if(user != null && oldPwdMw.equals(user.getPassword())){
			user.setPassword(newPwd);
			userManagerService.addObject(user);
			this.getAjaxMessagesJson().setMessage(true, "", "修改成功");
		}else{
			this.getAjaxMessagesJson().setMessage(false, "", "原始密码输入错误！");
		}
		return RESULT_AJAXJSON;
	}
	public UserStateService getUserStateService() {
		return userStateService;
	}
	public void setUserStateService(UserStateService userStateService) {
		this.userStateService = userStateService;
	}
	public UserStateService getState() throws Exception {
		return userStateService;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public String getLoginMessage() {
		return loginMessage;
	}
	public void setLoginMessage(String loginMessage) {
		this.loginMessage = loginMessage;
	}
	public UserManagerService getUserManagerService() {
		return userManagerService;
	}
	public void setUserManagerService(UserManagerService userManagerService) {
		this.userManagerService = userManagerService;
	}
	public String getOldPwd() {
		return oldPwd;
	}
	public void setOldPwd(String oldPwd) {
		this.oldPwd = oldPwd;
	}
	public String getNewPwd() {
		return newPwd;
	}
	public void setNewPwd(String newPwd) {
		this.newPwd = newPwd;
	}
}
